/*
 * Created by SharpDevelop.
 * User: Guy Fomi
 * Date: 2/6/2011
 * Time: 2:14 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace TomatoSynchronizer.Store
{
	/// <summary>
	/// Description of ManufacturerStore.
	/// </summary>
	public class ManufacturerStore
	{
		private Site _site;
		private HtmlWeb _client;
		
		public ManufacturerStore(Site site,HtmlWeb client)
		{
			_site = site;
			_client = client;
		}
		
		private IDictionary GetManufacturer(string manufacturerId)
		{
			List<IDictionary> entries = new List<IDictionary>();
			string url = _site.Url + "/admin/json.php?action=load_manufacturer&manufacturers_id=" + manufacturerId + "&module=manufacturers";
			
			HtmlDocument doc = _client.Load(url);
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "data")
				{					
					IDictionary manufacturer = (IDictionary)json[key];					
					if(manufacturer["manufacturers_image"] != null)
					{
						string image = manufacturer["manufacturers_image"].ToString();
						Utility.DownloadImage(_site.Url + "/images/manufacturers/" + image,"/images/manufacturers/");
					}
					entries.Add(manufacturer);
				}
			}			
			
			return entries[0];
		}
		
		public List<IDictionary> GetManufacturers()
		{
			List<IDictionary> records = new List<IDictionary>();
			
			HtmlDocument doc = _client.Load(_site.Url + "/admin/json.php?action=list_manufacturers&module=manufacturers");
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "records")
				{
					object[] recs = (object[])json[key];
					for(int i = 0;i < recs.Length;i++)
					{
						IDictionary record = (IDictionary)recs[i];	
						IDictionary manufacturer = GetManufacturer(record["manufacturers_id"].ToString());
						records.Add(manufacturer);												
					}									
				}
			}			
			
			return records;
		}		
	}
}
